<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Roles;
use App\Model\Permission;
use App\Tools\HgTool;
use Input;

class RolesController extends CommonController
{
    public function index(){
    	$roles = new Roles;
    	$permission = new Permission;
    	$tool = new HgTool;
    	$data['roleCount'] = $roles->count();
    	$data['roleAlls'] = $roles->orderBy('id','asc')->paginate(10);
    	foreach($data['roleAlls'] as $k=>$v){
    		if($v['pid']!=0){ //非超级管理员处理
				$v['permissionStr'] = $tool->arrToStr($permission->select('name')->whereIn('id',explode(',',$v['pid']))->get(),'name');
    		}else{
    			$v['permissionStr'] = '所有权限';
    		}
    		$data['roleAll'][$k] = $v;
    	}
    	return view('admin.role_list',$data);
    }

    public function add(Request $request){
    	$roles = new Roles;
    	$permission = new Permission;
    	$data['permissionAll'] = $permission->where('is_type',0)->get();
    	if($request->isMethod('post')){
    		$arr = Input::only('name','pid');
    		$arr['pid'] = implode(',',$arr['pid']);
    		$roles->insert($arr);
    		return redirect('/Admin/Roles/add');
    	}
    	return view('admin.role_add',$data);
    }

    public function edit(Request $request,$id){
    	$roles = new Roles;
    	$permission = new Permission;
    	$data['permissionAll'] = $permission->where('is_type',0)->get();
    	$data['roleInfo'] = $roles->find($id);
    	$data['permissionInfo'] = explode(',',$data['roleInfo']->pid);
    	if($request->isMethod('post')){
    		$arr = Input::only('name','pid');
    		$arr['pid'] = implode(',',$arr['pid']);
    		$roles->where('id',$id)->update($arr);
    		return redirect('/Admin/Roles/list');
    	}
    	return view('admin.role_edit',$data);
    }

    public function del(Request $request,$id){
    	$roles = new Roles;
    	$roles->where('id',$id)->delete();
    	return redirect('/Admin/Roles/list');
    }
}
